<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/2
 * Time: 10:30
 */

namespace app\api\controller;


use app\api\model\Activity as ActivityModel;//活动分类
use app\api\model\InstitutionalActivities as InstitutionalActivitiesModel;//活动
use app\api\model\Mechanism as MechanismModel;//机构
use app\api\model\MechanismMien as MechanismMienModel;//机构风采
use app\api\model\User as UserModel;
use think\Db;

class Mechanism extends Common
{
    /**
     * 我的机构
     */
    public function myMechanism()
    {
        $params = input('param.');
        //身份验证
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        
        $userModel = new UserModel();
        $result = $userModel->joinMechanism($params['user_id']);//所属机构ID
        //未登录或游客
        if(!$result['user_to_mechanism_id']){
//            return $this->apiError('w100', '暂未登录');
            return json_encode(['status'=>200, 'msg'=>'暂未登陆！', 'data'=>[]], 256);
        }
        //未加入任何机构，默认为-1
        if($result['user_to_mechanism_id'] == -1 || $result['user_attestation'] != 3) {
//            return $this->apiError(4001);
            return json_encode(['status'=>200, 'msg'=>'您当前还未加入任何机构，快去找到自己的组织吧！', 'data'=>[]], 256);
        }
        //我的机构
        $mechModel = new MechanismModel();
        $field = 'mechanism_id, mechanism_name, mechanism_intro, mechanism_logo';
        $info = $mechModel->mechanismInfo($result['user_to_mechanism_id'], $field);
        return $this->apiSuccess($info);
        
    }
    
    /**
     * 机构列表
     * page:当前页码
     */
    public function allMechanism()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        
        $mechModel = new MechanismModel();
        $field = 'mechanism_id, mechanism_name, mechanism_intro, mechanism_logo';
        $list = $mechModel->mechanismInfo('', $field, $params['page']);//机构列表
        return $this->apiSuccess($list);
    }
    
    /**
     * 获取机构详情
     * @return string|void
     * mechanism_id：机构ID
     */
    public function mechanismInfo()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        
        $mechanism_id = $params['mechanism_id'];
        $mechModel = new MechanismModel();
        $this->IDIsTrue($mechanism_id, $mechModel);//判断机构ID是否存在
        
        $field = 'mechanism_id, mechanism_name, mechanism_intro, mechanism_logo';
        $info = $mechModel->mechanismInfo($mechanism_id, $field);//机构详情
        
        $activityModel = new InstitutionalActivitiesModel();
        $count = $activityModel->activityTime($mechanism_id);//总时长&总次数
        if(!$count[0]['activityTime']) {
            $info['activityTime'] = 0;
        } else {
            $info['activityTime'] = $count[0]['activityTime'];//总时长
        }
        $info['num'] = $count[0]['num'];//总次数
        
        $maxNum = $activityModel->bestActivity($mechanism_id);//最优活动
        if(empty($maxNum)) {
            $info['maxNum'] = 0;
            $info['typeName'] = '暂无活动';
        } else {
            $str = '';
            foreach($maxNum as $key=>$va){
                $str .= ltrim($va, ',');
            }
            $str = rtrim($str, ',');//所有活动类型id组合成的一个字符串
            $arr = explode(',', $str);//转换成数组
            $new_arr = array_count_values($arr);//将数组按照数组元素出现次数重新生成数组
            asort($new_arr);//将数组按升序排序
            $arr_key = array_keys($new_arr);//活动类型ID的升序数组
            $arr_value = array_values($new_arr);//活动类型次数的升序数组
            $info['maxNum'] = end($arr_value);//最优活动次数
            $activity_id = end($arr_key);//最优活动ID
            $activityTypeModel = new ActivityModel();
            $info['typeName'] = $activityTypeModel->activityTypeName($activity_id);//最优活动名称
        }
        return $this->apiSuccess($info);
        
    }
    
    /**
     * 机构风采
     * @return string|void
     * mechanism_id：机构ID
     */
    public function mechanismMien(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        $mechanism_id = $params['mechanism_id'];
        
        $mecModel = new MechanismModel();
        $this->IDIsTrue($mechanism_id, $mecModel);//判断机构ID是否存在
        
        $mechanismMienModel = new MechanismMienModel();
        $field = 'mien_id, mien_url, mien_description, mechanism_id';
        $list = $mechanismMienModel->mienInfo($mechanism_id, $field);//机构风采
        return $this->apiSuccess($list);
    }
    
    /**
     * 获取机构的所有活动
     * @return false|\PDOStatement|string|\think\Collection|void
     * page：当前页码
     * mechanism_id：机构ID
     */
    public function mechanismActivity(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        $mechanism_id = $params['mechanism_id'];
        
        $mecModel = new MechanismModel();
        $this->IDIsTrue($mechanism_id, $mecModel);//判断机构ID是否存在
        
        $page = $params['page'];
        $field = 'id, activity_name, activity_address, activity_start_time, activity_end_time, 
                activity_status, activity_img, activity_id';
        $activityModel = new InstitutionalActivitiesModel();
        $lists = $activityModel->getActivitys($mechanism_id, $field, $page);//活动列表
        
        //将活动分类ID转换成活动分类名称
        foreach($lists as $key=>&$list){
            $list['activity_id'] = trim($list['activity_id'], ',');
            $activity_type_name = Db::table('up_activity')->where('id', 'IN', $list['activity_id'])->column('activity_name');
            $list['activity_type_name'] = implode(',', $activity_type_name);
        }
        return $this->apiSuccess($lists);
    }
    
    /**
     * 机构名称列表  用于搜索
     * @return string
     */
    public function mechanismList(){
        $mecModel = new MechanismModel();
        $list = $mecModel->getMechanismList();
        return $this->apiSuccess($list);
    }
    
    /**
     * 手动输入机构名称进行查询
     * name：输入的名称
     * page：当前页码
     */
    public function searchMechanism(){
        $params = input('param.');
        $name = $params['name'];
        $page = $params['page'];
        $mecModel = new MechanismModel();
        $list = $mecModel->getMechanismList($name, $page, 2);
        return $this->apiSuccess($list);
    }
    
    /**
     * 判断获取的机构ID是否存在
     * @param $mechanism_id  机构ID
     * @param $model   机构模型
     */
    protected function IDIsTrue($mechanism_id, $model){
        $result = $model->mechanismInfo($mechanism_id);
        if(!$result) {
            return $this->apiError(4002);
        }
    }
}